package com.flejay.dreamrecruiter.service.impl;

import java.util.Iterator;
import java.util.List;
import java.util.regex.Pattern;

import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;

import com.flejay.dreamrecruiter.model.AbstractTag;
import com.flejay.dreamrecruiter.service.ILoggingService;
import com.flejay.dreamrecruiter.service.IParsingEngineService;

@Singleton
@Named("parsingEngineService")
public class ParsingEngineService implements IParsingEngineService {

	@Inject
	@Named("logService")
	private ILoggingService logService;
	
	@Override
	public AbstractTag getFirstFoundTag(final String preparedLine, final List<AbstractTag> tags) {
		this.logService.debug(this.getClass(), "\n.abstractBlockMatches > preparedLine={},tags={}", new Object[]{preparedLine,tags});
		AbstractTag matchingTag = null;
		Boolean tagFound = false;
		Iterator<AbstractTag> tagIterator = tags.iterator();
		while (!tagFound && tagIterator.hasNext()){
			AbstractTag tag = tagIterator.next();
			Iterator<Pattern> regexIterator = tag.getRegexp().iterator();
			while (!tagFound && regexIterator.hasNext()){
				Pattern regex = regexIterator.next();
				if (regex.matcher(preparedLine).find()){
					matchingTag = tag;
					tagFound = true;
				}
			}
		}
		this.logService.debug(this.getClass(), "\n.blockMatches < matchingTag={}", matchingTag);
		return matchingTag;
	}

	@Override
	public AbstractTag getFirstMatchingTag(final String preparedLine, final List<AbstractTag> tags) {
		this.logService.debug(this.getClass(), "\n.abstractBlockMatches > preparedLine={},tags={}", new Object[]{preparedLine,tags});
		AbstractTag matchingTag = null;
		Boolean tagFound = false;
		Iterator<AbstractTag> tagIterator = tags.iterator();
		while (!tagFound && tagIterator.hasNext()){
			AbstractTag tag = tagIterator.next();
			Iterator<Pattern> regexIterator = tag.getRegexp().iterator();
			while (!tagFound && regexIterator.hasNext()){
				Pattern regex = regexIterator.next();
				if (regex.matcher(preparedLine).matches()){
					matchingTag = tag;
					tagFound = true;
				}
			}
		}
		this.logService.debug(this.getClass(), "\n.blockMatches < matchingTag={}", matchingTag);
		return matchingTag;
	}
}
